package wz

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"navi-mumbai/common/xerr"
	"net/http"
	"strconv"
	"time"
)

type QueryOrderReq struct {
	Last int64 `json:"last"` // 最近接收到的流水版本序号，0开始，结果会返回最新的
	Per  int64 `json:"per"`  // 每次拉取的数量，暂时访问 10 ~ 300
}

type QueryOrderData struct {
	Last  int64        `json:"last"`
	Count int64        `json:"count"`
	Per   int64        `json:"per"`
	Data  []*OrderData `json:"data"`
}

type OrderData struct {
	BetId      int64  `json:"bet_id"`
	RoundId    int64  `json:"round_id"`
	Username   string `json:"username"`
	CurrencyId int64  `json:"currency_id"`
	InstId     int64  `json:"inst_id"`
	GameId     int64  `json:"game_id"`
	Currency   string `json:"currency"`
	FreeBet    bool   `json:"free_bet"`
	Win        int64  `json:"win"`
	BetAmt     string `json:"bet_amt"`
	WinAmt     string `json:"win_amt"`
	Payout     string `json:"payout"`
	BetTime    int64  `json:"bet_time"`
	PayTime    int64  `json:"pay_time"`
	Uid        string `json:"uid"`
	Status     int64  `json:"status"`
	Ver        int64  `json:"ver"`
	Details    string `json:"details"`
}

type QueryOrderResp struct {
	Code int64           `json:"code"`
	Data *QueryOrderData `json:"data"`
}

const queryOrderURI = "wzgames/bet/statement"

func (r *HttpClient) QueryOrder(req *QueryOrderReq) (resp *QueryOrderResp, err error) {
	// md5
	stamp := strconv.FormatInt(time.Now().Unix(), 10)
	sign := md5v(r.Id + strconv.FormatInt(req.Per, 10) + strconv.FormatInt(req.Last, 10) + stamp + r.Secret)
	resp = &QueryOrderResp{}
	var rsp *resty.Response

	rsp, err = r.cli.R().SetHeader("Accept", "application/json").SetQueryParams(map[string]string{
		"operator": r.Id,
		"last":     strconv.FormatInt(req.Last, 10),
		"per":      strconv.FormatInt(req.Per, 10),
		"stamp":    stamp,
		"sign":     sign,
	}).SetResult(resp).SetError(resp).Post(r.Host + queryOrderURI)
	if err != nil {
		return
	}
	if rsp.IsError() {
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, rsp.Status())
		return
	}
	if resp.Code != http.StatusOK {
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, fmt.Sprintf("code:%d", resp.Code))
		return
	}

	return
}
